package leetcode.D200.T106;

import util.TreeNode;

/**
 * @File Info: leetcode -- <Solution>
 * @Author: 18362
 * @Create: 2022-03-15 16:00:25 星期二
 */

class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        return build(inorder, postorder, 0, inorder.length-1, 0, postorder.length-1);
    }

    private TreeNode build(int[] inorder, int[] postorder, int iLeft, int iRight, int pLeft, int pRight) {
        if (iLeft > iRight)
            return null;
        int mid = iLeft;
        for (int i=iLeft; i<=iRight; ++i) {
            if (inorder[i] == postorder[pRight]) {
                mid = i;
                break;
            }
        }
        TreeNode root = new TreeNode(postorder[pRight]);
        root.left = build(inorder, postorder, iLeft, mid-1, pLeft, pLeft+mid-iLeft-1);
        root.right = build(inorder, postorder, mid+1, iRight, pLeft+mid-iLeft, pRight-1);
        return root;
    }
}